/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-26 15:37:46
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-08 11:08:12
 * @FilePath: /vue3-admin/src/service/biz/useUser.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import {
    readUserList,
    UserListParam,
    readUserDetail,
    UserParam,
    createOrUpdateItem
} from '@/api/user';
import { ref } from 'vue';
import type { UserListItem, UserDetail } from '@/typings/api/user';

export { UserListParam, UserParam };

export const useUser = () => {
    const total = ref(0);
    const list = ref<UserListItem[]>([]);
    // const listParam = ref(new UserListParam());
    const loading = ref(false);

    const getList = (param: UserListParam) => {
        if (loading.value) return;
        loading.value = true;
        return readUserList(param)
            .then((res) => {
                list.value = res.data.records;
                total.value = res.data.total;
                return res;
            })
            .finally(() => {
                loading.value = false;
            });
    };

    const detail = ref<UserDetail>();
    const detailLoading = ref(false);

    const getDetail = (id: number) => {
        if (detailLoading.value) return;
        detailLoading.value = true;
        return readUserDetail(id)
            .then((res) => {
                detail.value = res.data;
                return res;
            })
            .finally(() => {
                detailLoading.value = false;
            });
    };

    const updateLoading = ref(false);
    const updateUser = (param: UserParam) => {
        if (updateLoading.value) return;
        updateLoading.value = true;
        return createOrUpdateItem(param).finally(() => {
            updateLoading.value = false;
        });
    };

    return {
        loading,
        total,
        list,
        getList,
        detail,
        detailLoading,
        getDetail,
        updateUser,
        updateLoading
    };
};
